package com.shensi.adminCollect.service.station.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.Page;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.adminCollect.domain.station.*;
import com.shensi.adminCollect.domain.station.dto.MerAccEntryDto;
import com.shensi.adminCollect.mapper.station.CashReceiptsMapper;
import com.shensi.adminCollect.mapper.station.StationMapper;
import com.shensi.adminCollect.service.station.CashReceiptsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * (CashReceipts)表服务实现类
 *
 * @author makejava
 * @since 2023-04-18 14:20:50
 */
@Service("cashReceiptsService")
public class CashReceiptsServiceImpl implements CashReceiptsService {


    @Autowired
    private CashReceiptsMapper cashReceiptsMapper;
    @Autowired
    private StationMapper stationMapper;

    /**
     * 分页查询
     *

     * @return 查询结果
     */
    @Override
    public Map<String, Object> queryByPage(Long id, String startingTime, String endTimeint, int page, int pageSize, String phoneNumber,Long stationId ,Long enterpriseId) {
        Map<String, Object> map=new HashMap<String,Object>();
        PageHelper.startPage(page,pageSize);
        List<SysCashReceipts> list=cashReceiptsMapper.queryAllByLimit(id,startingTime,endTimeint,phoneNumber,stationId,enterpriseId);

        map.put("pageInfo",  Page.PageInfo(new PageInfo(list)));

        map.put("conditionCount",cashReceiptsMapper.conditionCount(id,startingTime,endTimeint,phoneNumber,stationId,enterpriseId));
        map.put("count",cashReceiptsMapper.count(stationId,enterpriseId));
        return map;
    }

    /**
     * 账户信息
     *
     * @param
     * @return 实例对象
     */
    @Override
    public  List<NoInsensAccInfoVO> listStationMerAccInfo(String clearUrl) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if (current.getUser().getUserLevel() == null || current.getUser().getUserLevel().isEmpty()) {
            List<NoInsensAccInfoVO> zeroNoInsensAccInfo = new ArrayList<NoInsensAccInfoVO>();
            return zeroNoInsensAccInfo;
        }
        List<Station> stations = new ArrayList<Station>();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            stations = stationMapper.selectStationList(station);


        } else if ("2".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station = stationMapper.selectStationById(current.getUser().getStationId());
            stations.add(station);
        }

        List<String> merAccNos = new ArrayList<String>();
        for (Station stationitem : stations) {
            String clearAccount = stationitem.getClearAccount();
            if (clearAccount != null && !clearAccount.isEmpty()) {
                merAccNos.add(clearAccount);
            }
        }
        ListNoInsensAccInfoDTO merAccNoList = new ListNoInsensAccInfoDTO();
//        merAccNoList.setMerAccNoList(merAccNos);
        RestTemplate restTemplate = new RestTemplate();
        //        账户信息接口
        String listNoInsensAccInfoUrl = clearUrl + "/clear-platform/merAcc/listNoInsensAccInfo";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 设置请求体参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("merAccNoList", merAccNos);

        // 发送请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(listNoInsensAccInfoUrl, HttpMethod.POST, requestEntity, Map.class);
        Map<String, Object> responseMap = responseEntity.getBody();
// 解析返回值
        List<Map<String, Object>> responseData = (List<Map<String, Object>>) responseMap.get("data");
        List<NoInsensAccInfoVO> result = new ArrayList<>();
        if (responseData != null) {
            for (Map<String, Object> data : responseData) {
                NoInsensAccInfoVO accInfo = new NoInsensAccInfoVO();
                accInfo.setMerNo((String) data.get("merNo"));
                accInfo.setMerName((String) data.get("merName"));
                accInfo.setMerAccNo((String) data.get("merAccNo"));
                accInfo.setMerAccName((String) data.get("merAccName"));
                accInfo.setBankAcctName((String) data.get("bankAcctName"));
                accInfo.setBankCardNo((String) data.get("bankCardNo"));
                result.add(accInfo);
            }
        }
        return result;
    }

    /**
     * 交易记录
     *
     * @param
     * @return 实例对象
     */
    @Override
    public  Map<String, Object> queryNoInsensTrans(String clearUrl,QueryNoInsensTransDTO queryNoInsensTransDTO) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if (current.getUser().getUserLevel() == null || current.getUser().getUserLevel().isEmpty()) {
            Map<String, Object> zeroNoInsensAccInfo = new HashMap<>();
            return zeroNoInsensAccInfo;
        }
        List<Station> stations = new ArrayList<Station>();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            stations = stationMapper.selectStationList(station);


        } else if ("2".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station = stationMapper.selectStationById(current.getUser().getStationId());
            stations.add(station);
        }

        List<String> merAccNos = new ArrayList<String>();
        for (Station stationitem : stations) {
            String clearAccount = stationitem.getClearAccount();
            if (clearAccount != null && !clearAccount.isEmpty()) {
                merAccNos.add(clearAccount);
            }
        }
        ListNoInsensAccInfoDTO merAccNoList = new ListNoInsensAccInfoDTO();
//        merAccNoList.setMerAccNoList(merAccNos);
        RestTemplate restTemplate = new RestTemplate();
        //        账户信息接口
        String listNoInsensAccInfoUrl = clearUrl + "/clear-platform/merAcc/queryNoInsensTrans";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 设置请求体参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("startTime", queryNoInsensTransDTO.getStartTime());
        requestBody.put("endTime", queryNoInsensTransDTO.getEndTime());
        requestBody.put("merAccNo", queryNoInsensTransDTO.getMerAccNo());
        requestBody.put("txnAmt", queryNoInsensTransDTO.getTxnAmt());
        requestBody.put("status", queryNoInsensTransDTO.getStatus());
        requestBody.put("page", queryNoInsensTransDTO.getPage());
        requestBody.put("limit", queryNoInsensTransDTO.getLimit());

        // 发送请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(listNoInsensAccInfoUrl, HttpMethod.POST, requestEntity, Map.class);
        Map<String, Object> responseMap = responseEntity.getBody();
// 解析返回值
//        List<QueryNoInsensTransVO> result = (List<QueryNoInsensTransVO>) responseMap.get("data");    records
//        return result;

        Object data = responseMap.get("data");
        Map<String, Object> result = new HashMap<>();
        if (data != null && data instanceof Map) {
            Map<String, Object> dataMap = (Map<String, Object>) data;
            result = dataMap;
        }
        return result;
    }


    /**
     * 交易汇总
     *
     * @param
     * @return 实例对象
     */
    @Override
    public  QueryNoInsensTransSumVO queryNoInsensTransSum(String clearUrl,QueryNoInsensTransSumDTO queryNoInsensTransSumDTO) {
        List<String> list = new ArrayList<>();
        LoginUser current = SecurityUtils.getLoginUser();
        if (current.getUser().getUserLevel() == null || current.getUser().getUserLevel().isEmpty()) {
            QueryNoInsensTransSumVO zeroNoInsensAccInfo = new QueryNoInsensTransSumVO();
            return zeroNoInsensAccInfo;
        }
        List<Station> stations = new ArrayList<Station>();
        if ("1".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station.setEnterpriseId(current.getUser().getEnterpriseId());
            stations = stationMapper.selectStationList(station);


        } else if ("2".equals(current.getUser().getUserLevel())) {
            Station station = new Station();
            station = stationMapper.selectStationById(current.getUser().getStationId());
            stations.add(station);
        }

        List<String> merAccNos = new ArrayList<String>();
        for (Station stationitem : stations) {
            String clearAccount = stationitem.getClearAccount();
            if (clearAccount != null && !clearAccount.isEmpty()) {
                merAccNos.add(clearAccount);
            }
        }
        ListNoInsensAccInfoDTO merAccNoList = new ListNoInsensAccInfoDTO();
//        merAccNoList.setMerAccNoList(merAccNos);
        RestTemplate restTemplate = new RestTemplate();
        //        账户信息接口
        String listNoInsensAccInfoUrl = clearUrl + "/clear-platform/merAcc/queryNoInsensTransSum";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 设置请求体参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("startTime", queryNoInsensTransSumDTO.getStartTime());
        requestBody.put("endTime", queryNoInsensTransSumDTO.getEndTime());
        requestBody.put("merAccNo", queryNoInsensTransSumDTO.getMerAccNo());
        requestBody.put("txnAmt", queryNoInsensTransSumDTO.getTxnAmt());
        requestBody.put("status", queryNoInsensTransSumDTO.getStatus());


        // 发送请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(listNoInsensAccInfoUrl, HttpMethod.POST, requestEntity, Map.class);
        Map<String, Object> responseMap = responseEntity.getBody();

        Map<String, Object> resultMap = (Map<String, Object>) responseMap.get("data");

        QueryNoInsensTransSumVO result = new QueryNoInsensTransSumVO();

// 提现累计
        BigDecimal cashAmt = new BigDecimal(resultMap.get("cashAmt").toString());
        result.setCashAmt(cashAmt);

// 转入累计
        BigDecimal changeInAmt = new BigDecimal(resultMap.get("changeInAmt").toString());
        result.setChangeInAmt(changeInAmt);

// 转出累计
        BigDecimal changeOutAmt = new BigDecimal(resultMap.get("changeOutAmt").toString());
        result.setChangeOutAmt(changeOutAmt);

// 提现服务费
        BigDecimal cashServiceFee = new BigDecimal(resultMap.get("cashServiceFee").toString());
        result.setCashServiceFee(cashServiceFee);

// 划转服务费
        BigDecimal transferServiceFee = new BigDecimal(resultMap.get("transferServiceFee").toString());
        result.setTransferServiceFee(transferServiceFee);

        return result;
    }


    /**
     * 取服务费
     *
     * @param
     * @return 实例对象
     */
    @Override
    public Map<String, Object> getServiceFee(String clearUrl,MerAccGetServiceFeeDTO merAccGetServiceFeeDTO) {

        RestTemplate restTemplate = new RestTemplate();
        //        账户信息接口
        String listNoInsensAccInfoUrl = clearUrl + "/clear-platform/merAcc/getServiceFee";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 设置请求体参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("clearMerNo", merAccGetServiceFeeDTO.getClearMerNo());
        requestBody.put("merAccNo", merAccGetServiceFeeDTO.getMerAccNo());
        requestBody.put("txnType", merAccGetServiceFeeDTO.getTxnType());
        requestBody.put("txnAmt", merAccGetServiceFeeDTO.getTxnAmt());


        // 发送请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(listNoInsensAccInfoUrl, HttpMethod.POST, requestEntity, Map.class);
        Map<String, Object> responseMap = responseEntity.getBody();
// 解析返回值
//        Map<String, Object> responseData = (Map<String, Object>) responseMap.get("data");
//        MerAccGetServiceFeeVO result = new MerAccGetServiceFeeVO();
//        result.setServiceFee(BigDecimal.valueOf((Double) responseData.get("serviceFee")));
//        result.setActDeductionAmt(BigDecimal.valueOf((Double) responseData.get("actDeductionAmt")));
//        result.setActReceiveAmt(BigDecimal.valueOf((Integer) responseData.get("actReceiveAmt")));
        return responseMap;
    }


    /**
     * 取服务费
     *
     * @param
     * @return 实例对象
     */
    @Override
    public AjaxResult getEntrySum(String clearUrl, MerAccEntryDto merAccEntryDto) {

        RestTemplate restTemplate = new RestTemplate();
        //        账户信息接口
        String listNoInsensAccInfoUrl = clearUrl + "/clear-platform/merAcc/getEntrySum";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 设置请求体参数
        Map<String, Object> requestBody = new HashMap<>();

        requestBody.put("merAccNo", merAccEntryDto.getMerAccNo());
        requestBody.put("startTime", merAccEntryDto.getStartTime());
        requestBody.put("endTime", merAccEntryDto.getEndTime());
        // 发送请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(listNoInsensAccInfoUrl, HttpMethod.POST, requestEntity, Map.class);
        Map<String, Object> responseMap = responseEntity.getBody();
        return AjaxResult.success(responseMap);

    }


    @Override
    public Map<String, Object> queryBalance(String clearUrl,MerAccGetServiceFeeDTO merAccGetServiceFeeDTO) {

        RestTemplate restTemplate = new RestTemplate();
        //        账户信息接口
        String listNoInsensAccInfoUrl = clearUrl + "/clear-platform/merAcc/queryBalance";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 设置请求体参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("merNo", merAccGetServiceFeeDTO.getClearMerNo());
        requestBody.put("merAccNo", merAccGetServiceFeeDTO.getMerAccNo());


        // 发送请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(listNoInsensAccInfoUrl, HttpMethod.POST, requestEntity, Map.class);
        Map<String, Object> responseMap = responseEntity.getBody();
// 解析返回值
        Map<String, Object> result = (Map<String, Object>) responseMap.get("data");

        return result;
    }


    @Override
    public Map<String, Object> cash(String clearUrl,MerAccGetServiceFeeDTO merAccGetServiceFeeDTO) {
        LoginUser current = SecurityUtils.getLoginUser();
        Map<String, Object> requestBody = new HashMap<>();
        if (current.getUser().getUserLevel() == null || current.getUser().getUserLevel().isEmpty()) {
            requestBody.put("operator", "admin");
        }
        List<Station> stations = new ArrayList<Station>();
        if ("1".equals(current.getUser().getUserLevel())) {
            requestBody.put("operator", current.getUser().getUserName());
        } else if ("2".equals(current.getUser().getUserLevel())) {
            requestBody.put("operator", current.getUser().getUserName());
        }

        RestTemplate restTemplate = new RestTemplate();
        //        账户信息接口
        String listNoInsensAccInfoUrl = clearUrl + "/clear-platform/merAcc/cash";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 设置请求体参数

        requestBody.put("merNo", merAccGetServiceFeeDTO.getClearMerNo());
        requestBody.put("merAccNo", merAccGetServiceFeeDTO.getMerAccNo());
        requestBody.put("txnAmt", merAccGetServiceFeeDTO.getTxnAmt());

        SimpleDateFormat fmt = new SimpleDateFormat("ddHHmmss");
        String no = fmt.format(System.currentTimeMillis())+merAccGetServiceFeeDTO.getMerAccNo();
        requestBody.put("orderNo", no);
        // 发送请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(listNoInsensAccInfoUrl, HttpMethod.POST, requestEntity, Map.class);
        Map<String, Object> responseMap = responseEntity.getBody();
// 解析返回值
        Map<String, Object> result = (Map<String, Object>) responseMap.get("data");

        return result;
    }
    /**
     * 新增数据
     *
     * @param cashReceipts 实例对象
     * @return 实例对象
     */
    @Override
    public int add(SysCashReceipts cashReceipts) {

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cashReceipts.setCollectionTime(formatter.format(date));
        return  this.cashReceiptsMapper.insert(cashReceipts);
    }

    /**
     * 修改数据
     *
     * @param cashReceipts 实例对象
     * @return 实例对象
     */
    @Override
    public int edit(SysCashReceipts cashReceipts) {

       return this.cashReceiptsMapper.update(cashReceipts);

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public int deleteById(List<Long> id) {
        return this.cashReceiptsMapper.deleteById(id);
    }
}
